//
//  AudioMainViewController.m
//  OfficeEtc
//
//  Created by Wangli on 12-6-2.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "AudioMainViewController.h"
#import "AudioEntity.h"
#import "AppDelegate.h"
#import "RootViewController.h"
#import "AppDelegate.h"

#define MusicAlert @"musicTransAlert"
#define MusicCellImg 0x14

typedef enum {
    GetMusic_IPodType=0x30,
    GetMusic_LocalType,
    GetMusic_AllType
}GetMusic_Type;

typedef enum {
    MusicPlay_ShunXu =0x50,
    MusicPlay_Suiji,
    MusicPlay_DanXunHuan
}MusicPlay_Mode;

@interface AudioMainViewController ()
-(BOOL) playMusicByItem:(AudioEntity*)f_NowItem;
@end

@implementation AudioMainViewController
@synthesize m_MusicPath;

-(id) init
{
    if (self = [super init]) {
        NSArray *docFolders = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES ); 
        NSString* tDocPath = [docFolders lastObject];
        m_MusicPath = [tDocPath stringByAppendingPathComponent:@"music"];
        [m_MusicPath retain];

    }
    return self;
}

-(void) viewWillAppear:(BOOL)animated
{
    if (self.navigationItem.rightBarButtonItem == nil) {
        UIBarButtonItem* tEditBarBt = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStyleDone target:self action:@selector(docEditMode:)];
        self.navigationItem.rightBarButtonItem= tEditBarBt;
        [tEditBarBt release];
    }
    if (p_AllMusicItems) {
        [p_AllMusicItems release];
        p_AllMusicItems =nil;
    }
    [self checkIpodMusicContinueTrans];
    p_AllMusicItems = [NSMutableArray arrayWithArray:[self getAllMusicLocalAndIpod:GetMusic_AllType]];
    [p_AllMusicItems retain];
    [p_ListTableView reloadData];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    p_NowPlayIndex = -1;
	// Do any additional setup after loading the view.
    p_ListTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 40, 320, self.view.bounds.size.height-74) style:UITableViewStylePlain];
    p_ListTableView.delegate = self;
    p_ListTableView.dataSource = self;
    [self.view addSubview:p_ListTableView];
    
    p_MusicController = [[MusicController alloc] init];
    p_MusicController.m_ModelViewController = self;
    
    p_BottomBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 480-20-40-44, 320, 40)];
    p_BottomBar.tintColor = [UIColor lightGrayColor];
    [self.view addSubview:p_BottomBar];
    
    UIBarButtonItem* tBarBtItem0 = [[UIBarButtonItem alloc] initWithTitle:@"wifi" style:UIBarButtonItemStyleBordered target:self action:@selector(toolButtonPressed:)];
    tBarBtItem0.width =62;
    tBarBtItem0.tag = 30;
    UIBarButtonItem* tBarBtItem1 = [[UIBarButtonItem alloc] initWithTitle:@"ftp" style:UIBarButtonItemStyleBordered target:self action:@selector(toolButtonPressed:)];
    tBarBtItem1.width =62;
    tBarBtItem1.tag = 31;
    UIBarButtonItem* tBarBtItem2 = [[UIBarButtonItem alloc] initWithTitle:@"ipod转换" style:UIBarButtonItemStyleBordered target:self action:@selector(toolButtonPressed:)];
    tBarBtItem2.width =84;
    tBarBtItem2.tag = 32;
    UIBarButtonItem* tBarBtItem3 = [[UIBarButtonItem alloc] initWithTitle:@"顺序播放" style:UIBarButtonItemStyleBordered target:self action:@selector(toolButtonPressed:)];
    tBarBtItem3.width =88;
    tBarBtItem3.tag = 33;
    [p_BottomBar setItems:[NSArray arrayWithObjects:tBarBtItem0,tBarBtItem1,tBarBtItem2,tBarBtItem3,nil]];
    [tBarBtItem0 release];
    [tBarBtItem1 release];
    [tBarBtItem2 release];
    [tBarBtItem3 release];
    p_BottomBar.hidden =YES;
    
    p_PlayImg = [[UIImage imageNamed:@"musicplay.png"] retain];
    p_PauseImg = [[UIImage imageNamed:@"musicpause.png"] retain];
    p_PlayButtonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
    [p_PlayButtonView setBackgroundColor:[UIColor lightGrayColor]];
    for (int i=0; i<4; i++) {
        UIButton* tButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [tButton setFrame:CGRectMake(30+i*70, 2, 36, 36)];
        [tButton addTarget:self action:@selector(musicButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        tButton.tag = i;
        switch (i) {
            case 0:
                [tButton setBackgroundImage:[UIImage imageNamed:@"musicstop.png"] forState:UIControlStateNormal];
                break;
            case 1:
                [tButton setBackgroundImage:[UIImage imageNamed:@"musicback.png"] forState:UIControlStateNormal];
                break;
            case 2:
                [tButton setBackgroundImage:p_PlayImg forState:UIControlStateNormal];
                break;
            case 3:
                [tButton setBackgroundImage:[UIImage imageNamed:@"musicnext.png"] forState:UIControlStateNormal];
                break;
        }
        [p_PlayButtonView addSubview:tButton];
    }
    [self.view addSubview:p_PlayButtonView];
        
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(MPMusicStateChanged:) name:MPMusicPlayerControllerPlaybackStateDidChangeNotification object:nil];
    
    p_PlayMode = MusicPlay_ShunXu;
    
    p_PlayingImg = [UIImage imageNamed:@"playing.png"];
    [p_PlayingImg retain];
    
    p_SliderCheckTimer = nil;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [p_ListTableView release];
    p_ListTableView = nil;
    [p_BottomBar release];
    p_BottomBar = nil;
    [m_MusicPath release];
    m_MusicPath = nil;
    [p_AllMusicItems release];
    p_AllMusicItems =nil;
    [p_PlayButtonView release];
    p_PlayButtonView = nil;
    [p_PlayImg release];
    p_PlayImg = nil;
    [p_PauseImg release];
    p_PauseImg = nil;
    [p_LocalPlayer release];
    p_LocalPlayer =nil;
    [p_MusicController release];
    p_MusicController = nil;
    [p_PlayingImg release];
    p_PlayingImg = nil;
    [p_TimerSlider release];
    p_TimerSlider =nil;
    [p_PlayName release];
    p_PlayName =nil;
    [p_TimeMusic release];
    p_TimeMusic = nil;
}

-(void) dealloc
{
    [super dealloc];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [p_ListTableView release];
    [p_BottomBar release];
    [m_MusicPath release];
    [p_AllMusicItems release];
    [p_PlayButtonView release];
    [p_PlayImg release];
    [p_PauseImg release];
    [p_LocalPlayer release];
    [p_MusicController release];
    [p_PlayingImg release];
    [p_TimerSlider release];
    [p_PlayName release];
    [p_TimeMusic release];
}

#pragma mark-
#pragma mark UITableViewDelegate
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 34;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView* tTimeView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 34)] autorelease];
    [tTimeView setBackgroundColor:[UIColor clearColor]];
    UIView* tColorView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 34)];
    [tColorView setBackgroundColor:[UIColor lightGrayColor]];
    tColorView.alpha =0.9f;
    [tTimeView addSubview:tColorView];
    [tColorView release];
    if (p_TimeMusic == nil) {
        p_TimeMusic = [[UILabel alloc] initWithFrame:CGRectMake(274, 14, 40, 12)];
        [p_TimeMusic setBackgroundColor:[UIColor clearColor]];
        [p_TimeMusic setFont:[UIFont systemFontOfSize:9.f]];
        p_TimeMusic.textAlignment = UITextAlignmentCenter;
    }
    [tTimeView addSubview:p_TimeMusic];
    
    if (p_PlayName == nil) {
        p_PlayName = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 16)];
        [p_PlayName setBackgroundColor:[UIColor clearColor]];
        [p_PlayName setFont:[UIFont systemFontOfSize:14.f]];
        p_PlayName.textAlignment = UITextAlignmentCenter;
    }
    [tTimeView addSubview:p_PlayName];

    if (p_TimerSlider == nil) {
        p_TimerSlider = [[UISlider alloc] initWithFrame:CGRectMake(20, 10, 260, 12)];
        [p_TimerSlider addTarget:self action:@selector(sliderChanged:) forControlEvents:UIControlEventValueChanged];
        p_TimerSlider.minimumValue =0.f;
        p_TimerSlider.maximumValue =0.f;
    }
    [tTimeView addSubview:p_TimerSlider];
    return tTimeView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44.f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    int row = [indexPath row];
    NSMutableArray* tFlashRows = [NSMutableArray array];
    [tFlashRows addObject:indexPath];
    if (p_NowPlayIndex >= 0 && p_NowPlayIndex != row) {
        NSIndexPath* tOldIndexPath = [NSIndexPath indexPathForRow:p_NowPlayIndex inSection:0];
        [tFlashRows addObject:tOldIndexPath];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    AudioEntity* tAEntity = [p_AllMusicItems objectAtIndex:row];
    if ([tAEntity.canplay intValue] == Music_CanPlay &&
        [tAEntity.ipodfileexist boolValue]) {
        p_NowPlayIndex = row;;
        if ([self playMusicByItem:tAEntity]) {
            UIButton* tPlayBtt = (UIButton*)[p_PlayButtonView viewWithTag:2];
            [tPlayBtt setBackgroundImage:p_PauseImg forState:UIControlStateNormal];
            [tableView reloadRowsAtIndexPaths:tFlashRows withRowAnimation:UITableViewRowAnimationNone];
        }
    }else {
        if ([tAEntity.canplay intValue] == Music_TransFail) {
            //重新转换
        }else if([tAEntity.canplay intValue] == Music_CanNotPlay){
            //不支持的格式播放
        }else if([tAEntity.ipodfileexist boolValue]){
            //文件已经不存在
        }
    }
}
#pragma mark-
#pragma mark UITableViewDataSource
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    int row =[indexPath row];
    AudioEntity* tItem= [p_AllMusicItems objectAtIndex:row];
    if (p_NowPlayIndex == row) {
        if (p_LocalPlayer) {
            if ([p_LocalPlayer isPlaying]) {
                [p_LocalPlayer stop];
            }
            [p_LocalPlayer release];
            p_LocalPlayer = nil;
        }
        [p_PlayName setText:@""];
        [p_TimeMusic setText:@""];
        [p_TimerSlider setValue:0.f];
    }
    if (p_AllMusicItems) {
        [p_AllMusicItems release];
        p_AllMusicItems = nil;
    }
    [self deleteMusicItem:tItem];
    p_AllMusicItems = [NSMutableArray arrayWithArray:[self getAllMusicLocalAndIpod:GetMusic_AllType]];
    [p_AllMusicItems retain];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [p_AllMusicItems count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    int row = [indexPath row];
    static NSString* tNameDeCell = @"memocell";
    UITableViewCell* tCell = nil;
    tCell = [tableView dequeueReusableCellWithIdentifier:tNameDeCell];
    if (tCell == nil) {
        tCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tNameDeCell] autorelease];
        UIImageView* tShowPlay = [[UIImageView alloc] initWithFrame:CGRectMake(280, 10, 24, 24)];
        tShowPlay.tag = MusicCellImg;
        [tCell addSubview:tShowPlay];
        [tShowPlay release];
    }
    AudioEntity* tItem= [p_AllMusicItems objectAtIndex:row];
    Music_Play tPlayStatus = [tItem.canplay intValue];
    [tCell.textLabel setFont:[UIFont systemFontOfSize:16.f]];
    
    UIImageView* tShowPlay =(UIImageView*)[tCell viewWithTag:MusicCellImg];
    [tShowPlay setImage:nil];
    if (p_NowPlayIndex >= 0 && p_NowPlayIndex == row) {
        [tShowPlay setImage:p_PlayingImg];
    }

    [tCell.textLabel setTextColor:[UIColor redColor]];
    if (tPlayStatus == Music_Transing) {
        tCell.textLabel.text =[NSString stringWithFormat:@"%@(转换中)",tItem.muiscname];
    }else if (tPlayStatus == Music_TransFail){
        tCell.textLabel.text =[NSString stringWithFormat:@"%@(转换失败)",tItem.muiscname];
    }else if(tPlayStatus == Music_CanNotPlay){
        tCell.textLabel.text =[NSString stringWithFormat:@"%@(不支持的格式)",tItem.muiscname];
    }else {
        [tCell.textLabel setTextColor:[UIColor blackColor]];
        tCell.textLabel.text =tItem.muiscname; 
    }

    return tCell;
}


#pragma mark-
#pragma mark MusicTableViewControllerDelegate
-(void) musicIopLibTransFinish:(NSString*)f_FileName
{
    NSLog(@"ipod file trans ok =%@",f_FileName);
    AppDelegate* tAppDelegate =(AppDelegate*)[UIApplication sharedApplication].delegate;
    NSError* tError = nil;
    NSEntityDescription* tEntDes = [NSEntityDescription entityForName:@"AudioEntity" inManagedObjectContext:tAppDelegate.managedObjectContext];
    NSFetchRequest* tFectReq = [[NSFetchRequest alloc] init];
    [tFectReq setEntity:tEntDes];
    NSPredicate* tIpodPre =[NSPredicate predicateWithFormat:@"(musictype == %d)AND(musicasseturl == %@)",Music_IPod,f_FileName];
    [tFectReq setPredicate:tIpodPre];
    NSArray* tAllMusic= [tAppDelegate.managedObjectContext executeFetchRequest:tFectReq error:&tError];
    [tFectReq release];
    if (tError!= nil) {
        NSLog(@"get path=%@ AudioEntity error =%@",f_FileName,[tError description]);
    }else {
        if ([tAllMusic count] == 1) {
            AudioEntity* tAEntity =[tAllMusic lastObject];
            tAEntity.canplay = [NSNumber numberWithInt:Music_CanPlay];
            tAEntity.ipodfileexist = [NSNumber numberWithBool:YES];
            [tAppDelegate.managedObjectContext save:&tError];
            if (tError != nil) {
                NSLog(@"changed canplay error =%@",[tError description]);
            }else {
                [p_ListTableView reloadData];
            }
        }else {
            NSLog(@"none fail path in data base =%@",f_FileName);
        }
    }
}
-(void) musicIopLibTransError:(NSString*)f_FileName
{
    NSLog(@"ipod file trans error =%@",f_FileName);
    AppDelegate* tAppDelegate =(AppDelegate*)[UIApplication sharedApplication].delegate;
    NSError* tError = nil;
    NSEntityDescription* tEntDes = [NSEntityDescription entityForName:@"AudioEntity" inManagedObjectContext:tAppDelegate.managedObjectContext];
    NSFetchRequest* tFectReq = [[NSFetchRequest alloc] init];
    [tFectReq setEntity:tEntDes];
    NSPredicate* tIpodPre =[NSPredicate predicateWithFormat:@"(musictype == %d)AND(musicasseturl == %@)",Music_IPod,f_FileName];
    [tFectReq setPredicate:tIpodPre];
    NSArray* tAllMusic= [tAppDelegate.managedObjectContext executeFetchRequest:tFectReq error:&tError];
    [tFectReq release];
    if (tError!= nil) {
        NSLog(@"get path=%@ AudioEntity error =%@",f_FileName,[tError description]);
    }else {
        if ([tAllMusic count] == 1) {
            AudioEntity* tAEntity =[tAllMusic lastObject];
            tAEntity.canplay = [NSNumber numberWithInt:Music_TransFail];
            [tAppDelegate.managedObjectContext save:&tError];
            if (tError != nil) {
                NSLog(@"changed Music_TransFail error =%@",[tError description]);
            }else {
                [p_ListTableView reloadData];
            }
        }else {
            NSLog(@"none fail path in data base =%@",f_FileName);
        }
    }
}

- (void) musicTableViewControllerDidFinish: (MusicController *) controller
{
    if (p_AllMusicItems) {
        [p_AllMusicItems release];
        p_AllMusicItems =nil;
    }
    p_AllMusicItems = [NSMutableArray arrayWithArray:[self getAllMusicLocalAndIpod:GetMusic_AllType]];
    [p_AllMusicItems retain];
    [p_ListTableView reloadData];
}
- (void) updatePlayerQueueWithMediaCollection: (MPMediaItemCollection *) mediaItemCollection
{
    if (mediaItemCollection) {
        AppDelegate* tAppDelegate =(AppDelegate*)[UIApplication sharedApplication].delegate;
        NSError* tError = nil;
		for (MPMediaItem* tIPodItem in mediaItemCollection.items) {
            NSString* tNameStr = [tIPodItem valueForProperty:MPMediaItemPropertyTitle];
            NSEntityDescription* tEntDes = [NSEntityDescription entityForName:@"AudioEntity" inManagedObjectContext:tAppDelegate.managedObjectContext];
            NSPredicate* tPred = [NSPredicate predicateWithFormat:@"muiscname == %@",tNameStr];
            NSFetchRequest* tFectReq = [[NSFetchRequest alloc] init];
            [tFectReq setEntity:tEntDes];
            [tFectReq setPredicate:tPred];
            NSArray* tArrID= [tAppDelegate.managedObjectContext executeFetchRequest:tFectReq error:&tError];
            [tFectReq release];
            if (tError!= nil) {
                NSLog(@"predicate AudioEntity with muiscname error =%@",[tError description]);
            }else {
                if ([tArrID count] == 0) {
                    AudioEntity* tInEntDes = (AudioEntity*)[NSEntityDescription insertNewObjectForEntityForName:@"AudioEntity" inManagedObjectContext:tAppDelegate.managedObjectContext];
                    tInEntDes.musictype =[NSNumber numberWithInt:Music_IPod];
                    tInEntDes.muiscname = [tIPodItem valueForProperty:MPMediaItemPropertyTitle];
                    tInEntDes.canplay = [NSNumber numberWithInt:Music_Transing];
                    tInEntDes.ipodfileexist = [NSNumber numberWithBool:NO];
                    NSArray *docFolders = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES ); 
                    NSString* tDocPath = [docFolders lastObject];
                    NSString* tMusicPath = [tDocPath stringByAppendingPathComponent:@"music"];
                    NSString *exportFile = [tMusicPath stringByAppendingPathComponent: [NSString stringWithFormat:@"%@.m4a",tInEntDes.muiscname]];
                    tInEntDes.musicasseturl = exportFile;
                    [tAppDelegate.managedObjectContext save:&tError];
                    if (tError != nil) {
                        NSLog(@"save new ipod music in database error =%@",[tError description]);
                    }else {
                        if (p_AllMusicItems) {
                            [p_AllMusicItems release];
                            p_AllMusicItems =nil;
                        }
                        p_AllMusicItems = [NSMutableArray arrayWithArray:[self getAllMusicLocalAndIpod:GetMusic_AllType]];
                        [p_AllMusicItems retain];
                        [p_ListTableView reloadData];
                    }
                }
            }
        }
        
        if ([mediaItemCollection.items count] > 2) {
            NSUserDefaults* tUDefault =[NSUserDefaults standardUserDefaults];
            NSNumber* tAlertV = [tUDefault objectForKey:MusicAlert];
            if (tAlertV == nil || [tAlertV boolValue]) {
                UIAlertView* tAlertV = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"音乐库里歌曲转换到本地应用文件需要花费一些时间请耐性等待(平均一首歌15秒左右)" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:@"不再提醒",nil];
                [tAlertV show];
                [tAlertV release];
            }
        }
	}
}

/*
无压缩硬转
-(void) convertTapped:(MPMediaItem*)f_Song {
	// set up an AVAssetReader to read from the iPod Library
	NSURL *assetURL = [f_Song valueForProperty:MPMediaItemPropertyAssetURL];
	AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:assetURL options:nil];
    
	NSError *assetError = nil;
	AVAssetReader *assetReader =
    [[AVAssetReader assetReaderWithAsset:songAsset
                                   error:&assetError]
     retain];
	if (assetError) {
		NSLog (@"error: %@", assetError);
		return;
	}
    AVAssetReaderOutput *assetReaderOutput =
	[[AVAssetReaderAudioMixOutput
	  assetReaderAudioMixOutputWithAudioTracks:songAsset.tracks
      audioSettings: nil]
     retain];
    if (! [assetReader canAddOutput: assetReaderOutput]) {
        NSLog (@"can't add reader output... die!");
        return;
    }
    [assetReader addOutput: assetReaderOutput];
    
    NSArray *dirs = NSSearchPathForDirectoriesInDomains
    (NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectoryPath = [dirs objectAtIndex:0];
    NSString *exportPath = [[documentsDirectoryPath
                             stringByAppendingPathComponent:@"fuckname"]
                            retain];
    if ([[NSFileManager defaultManager] fileExistsAtPath:exportPath]) {
        [[NSFileManager defaultManager] removeItemAtPath:exportPath
                                                   error:nil];
    }
    NSURL *exportURL = [NSURL fileURLWithPath:exportPath];
    
    AVAssetWriter *assetWriter =
	[[AVAssetWriter assetWriterWithURL:exportURL
                              fileType:AVFileTypeCoreAudioFormat
                                 error:&assetError]
     retain];
    if (assetError) {
        NSLog (@"error: %@", assetError);
        return;
    }
    
    AudioChannelLayout channelLayout;
    memset(&channelLayout, 0, sizeof(AudioChannelLayout));
    channelLayout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
    NSDictionary *outputSettings =
    [NSDictionary dictionaryWithObjectsAndKeys:
     [NSNumber numberWithInt:kAudioFormatLinearPCM], AVFormatIDKey,
     [NSNumber numberWithFloat:44100.0], AVSampleRateKey,
     [NSNumber numberWithInt:2], AVNumberOfChannelsKey,
     [NSData dataWithBytes:&channelLayout length:sizeof(AudioChannelLayout)],
     AVChannelLayoutKey,
     [NSNumber numberWithInt:16], AVLinearPCMBitDepthKey,
     [NSNumber numberWithBool:NO], AVLinearPCMIsNonInterleaved,
     [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,
     [NSNumber numberWithBool:NO], AVLinearPCMIsBigEndianKey,
     nil];
    
    AVAssetWriterInput *assetWriterInput =
	[[AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeAudio
                                        outputSettings:outputSettings]
     retain];
    if ([assetWriter canAddInput:assetWriterInput]) {
        [assetWriter addInput:assetWriterInput];
    } else {
        NSLog (@"can't add asset writer input... die!");
        return;
    }
    assetWriterInput.expectsMediaDataInRealTime = NO;
    
    [assetWriter startWriting];
    [assetReader startReading];
    AVAssetTrack *soundTrack = [songAsset.tracks objectAtIndex:0];
    CMTime startTime = CMTimeMake (0, soundTrack.naturalTimeScale);
    [assetWriter startSessionAtSourceTime: startTime];
    
    __block UInt64 convertedByteCount = 0;
    dispatch_queue_t mediaInputQueue =
	dispatch_queue_create("mediaInputQueue", NULL);
    [assetWriterInput requestMediaDataWhenReadyOnQueue:mediaInputQueue
                                            usingBlock: ^
     {
         
         while (assetWriterInput.readyForMoreMediaData) {
             CMSampleBufferRef nextBuffer =
             [assetReaderOutput copyNextSampleBuffer];
             if (nextBuffer) {
                 // append buffer
                 [assetWriterInput appendSampleBuffer: nextBuffer];
                 // update ui
                 convertedByteCount +=
                 CMSampleBufferGetTotalSampleSize (nextBuffer);
                 NSNumber *convertedByteCountNumber =
                 [NSNumber numberWithLong:convertedByteCount];
                 [self performSelectorOnMainThread:@selector(updateSizeLabel:)
                                        withObject:convertedByteCountNumber
                                     waitUntilDone:NO];
             } else {
                 // done!
                 [assetWriterInput markAsFinished];
                 [assetWriter finishWriting];
                 [assetReader cancelReading];
                 NSDictionary *outputFileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:exportPath
                  error:nil];
                 //NSLog (@"done. file size is %d",[outputFileAttributes fileSize]);
                 NSNumber *doneFileSize = [NSNumber numberWithLong:
                                           [outputFileAttributes fileSize]];
                 [self performSelectorOnMainThread:@selector(updateCompletedSizeLabel:)
                                        withObject:doneFileSize
                                     waitUntilDone:NO];
                 // release a lot of stuff
                 [assetReader release];
                 [assetReaderOutput release];
                 [assetWriter release];
                 [assetWriterInput release];
                 [exportPath release];
                 break;
             }
         }
	 }];
	NSLog (@"bottom of convertTapped:");
}

-(void) updateSizeLabel:(NSNumber*)tNumber
{
    NSLog(@"aaa =%d",[tNumber intValue]);
}
-(void) updateCompletedSizeLabel:(NSNumber*) donesize
{
    
}*/
#pragma mark-
#pragma mark music-ipod-tool

-(void) musicSliderUpdate
{
    p_TimerSlider.value = p_LocalPlayer.currentTime;
}

-(void) sliderChanged:(UISlider*)f_Slider
{
    p_LocalPlayer.currentTime = f_Slider.value;
}

/**
 @disscusion 获得f_PreName ipod音乐MPMediaQuery
 */
-(MPMediaQuery*) getChoicedIpodMusicItems:(NSString*) f_PreName
{
    AppDelegate* tAppDelegate =(AppDelegate*)[UIApplication sharedApplication].delegate;
    NSError* tError = nil;
    NSEntityDescription* tEntDes = [NSEntityDescription entityForName:@"AudioEntity" inManagedObjectContext:tAppDelegate.managedObjectContext];
    NSPredicate* tPred = [NSPredicate predicateWithFormat:@"(muiscname == %@) AND (musictype == %d)",f_PreName,Music_IPod];
    NSFetchRequest* tFectReq = [[NSFetchRequest alloc] init];
    [tFectReq setEntity:tEntDes];
    [tFectReq setPredicate:tPred];
    NSArray* tChoicedIPods= [tAppDelegate.managedObjectContext executeFetchRequest:tFectReq error:&tError];
    [tFectReq release];
    if (tError!= nil) {
        NSLog(@"predicate AudioEntity with musictype and muiscname error =%@",[tError description]);
        return  nil;
    }else {
        if ([tChoicedIPods count] > 0) {
            MPMediaQuery* tMMQuery = [MPMediaQuery songsQuery];
            for (AudioEntity* tItem in tChoicedIPods) {
                MPMediaPropertyPredicate *tPred = [MPMediaPropertyPredicate predicateWithValue:tItem.muiscname forProperty:MPMediaItemPropertyTitle];
                [tMMQuery addFilterPredicate:tPred];
                if ([[tMMQuery items] count] >0) {
                    return tMMQuery;
                }else {
                    //数据库内的一条ipod 音乐纪录在 ipod 内已经找不到了
                    tItem.ipodfileexist = [NSNumber numberWithBool:NO];
                    [tAppDelegate.managedObjectContext save:&tError];
                    if (tError != nil) {
                        NSLog(@"save ipodfileexist error =%@",[tError description]);
                    }
                    return nil;
                }
            }
        }else {
            NSLog(@" not found AudioEntity by muiscname =%@",f_PreName);
            return nil;
        }
    }
    return nil;
}

/**
 @disscusion 获得所有 或者 本地 或者ipod 的音乐 对象
 */
-(NSArray*) getAllMusicLocalAndIpod:(NSInteger) f_Type
{
    AppDelegate* tAppDelegate =(AppDelegate*)[UIApplication sharedApplication].delegate;
    NSError* tError = nil;
    NSEntityDescription* tEntDes = [NSEntityDescription entityForName:@"AudioEntity" inManagedObjectContext:tAppDelegate.managedObjectContext];
    NSFetchRequest* tFectReq = [[NSFetchRequest alloc] init];
    [tFectReq setEntity:tEntDes];
    if (f_Type == GetMusic_IPodType) {
        NSPredicate* tIpodPre =[NSPredicate predicateWithFormat:@"musictype == %d",Music_IPod];
        [tFectReq setPredicate:tIpodPre];
    }else if(f_Type == GetMusic_LocalType){
        NSPredicate* tLocalPre =[NSPredicate predicateWithFormat:@"musictype == %d",Music_LocalFile];
        [tFectReq setPredicate:tLocalPre];
    }
    NSArray* tAllMusic= [tAppDelegate.managedObjectContext executeFetchRequest:tFectReq error:&tError];
    [tFectReq release];
    if (tError!= nil) {
        NSLog(@"get all AudioEntity error =%@",[tError description]);
        return  nil;
    }else {
        return tAllMusic;
    }
}

/**
 用户手动删除一个音乐对象
 */
-(BOOL) deleteMusicItem:(AudioEntity*)f_DelItem
{
    NSError* tError = nil;
    if ([f_DelItem.musictype intValue]== Music_LocalFile) {
        //本地文件的删除
        NSFileManager* tFManager=[NSFileManager defaultManager];
        if ([tFManager fileExistsAtPath:f_DelItem.muiscurl]) {
            if (![tFManager removeItemAtPath:f_DelItem.muiscurl error:&tError]) {
                NSLog(@"loacl muisc file remove error =%@",[tError description]);
                return NO;
            }else {
                return [self deleteMusicItemByPath:f_DelItem.muiscurl];
            }
        }else {
            NSLog(@"loacl remove path file not exist path =%@",f_DelItem.muiscurl);
            return NO;
        }
    }else if([f_DelItem.musictype intValue]== Music_IPod){
         //ipod 删除数据纪录
        AppDelegate* tAppDelegate =(AppDelegate*)[UIApplication sharedApplication].delegate;
        NSError* tError = nil;
        //检查是已经有此条纪录
        NSEntityDescription* tEntDes = [NSEntityDescription entityForName:@"AudioEntity" inManagedObjectContext:tAppDelegate.managedObjectContext];
        NSPredicate* tPred = [NSPredicate predicateWithFormat:@"muiscname == %@",f_DelItem.muiscname];
        NSFetchRequest* tFectReq = [[NSFetchRequest alloc] init];
        [tFectReq setEntity:tEntDes];
        [tFectReq setPredicate:tPred];
        NSArray* tDelIpodArr= [tAppDelegate.managedObjectContext executeFetchRequest:tFectReq error:&tError];
        [tFectReq release];
        if (tError!= nil) {
            NSLog(@"get muiscname item error when delete =%@",[tError description]);
            return NO;
        }else {
            if ([tDelIpodArr count]>0) {
                AudioEntity* tIpodItem = [tDelIpodArr lastObject];
                [tAppDelegate.managedObjectContext deleteObject:tIpodItem];
                [tAppDelegate.managedObjectContext save:&tError];
                if (tError != nil) {
                    NSLog(@"delete muiscname in database error =%@",[tError description]);
                    return NO;
                }
                return YES;
            }else {
                NSLog(@"delete ipoditem not found in database");
                return NO;
            }
        }
    }
    return YES;
}


/**
 删除指定目录的音乐 --wifi ---ftp --手动
 */
-(BOOL) deleteMusicItemByPath:(NSString*) f_DelPath
{
    AppDelegate* tAppDelegate =(AppDelegate*)[UIApplication sharedApplication].delegate;
    NSError* tError = nil;
    //检查是已经有此条纪录
    NSEntityDescription* tEntDes = [NSEntityDescription entityForName:@"AudioEntity" inManagedObjectContext:tAppDelegate.managedObjectContext];
    NSPredicate* tPred = [NSPredicate predicateWithFormat:@"muiscurl == %@",f_DelPath];
    NSFetchRequest* tFectReq = [[NSFetchRequest alloc] init];
    [tFectReq setEntity:tEntDes];
    [tFectReq setPredicate:tPred];
    NSArray* tDelArr= [tAppDelegate.managedObjectContext executeFetchRequest:tFectReq error:&tError];
    [tFectReq release];
    if (tError!= nil) {
        NSLog(@"check file is exits error =%@",[tError description]);
        return NO;
    }else {
        if ([tDelArr count] >0) {
            AudioEntity* tDelObject = [tDelArr lastObject];
            [tAppDelegate.managedObjectContext deleteObject:tDelObject];
            [tAppDelegate.managedObjectContext save:&tError];
            if (tError != nil) {
                NSLog(@"delete music item error =%@",[tError description]);
                return NO;
            }
            if (p_AllMusicItems) {
                [p_AllMusicItems release];
                p_AllMusicItems =nil;
            }
            p_AllMusicItems = [NSMutableArray arrayWithArray:[self getAllMusicLocalAndIpod:GetMusic_AllType]];
            [p_AllMusicItems retain];
            [p_ListTableView reloadData];
        }else {
            NSLog(@"delete music file not found in database path =%@",f_DelPath);
        }
    }
    return YES;
}

/**
 增加指定目录下的音乐 --wifi ---ftp 的添加
 */
-(void) addMusicItemByPath:(NSString*) f_AddPath
{
    AppDelegate* tAppDelegate =(AppDelegate*)[UIApplication sharedApplication].delegate;
    NSError* tError = nil;
    //检查是已经有此条纪录
    NSEntityDescription* tEntDes = [NSEntityDescription entityForName:@"AudioEntity" inManagedObjectContext:tAppDelegate.managedObjectContext];
    NSPredicate* tPred = [NSPredicate predicateWithFormat:@"muiscurl == %@",f_AddPath];
    NSFetchRequest* tFectReq = [[NSFetchRequest alloc] init];
    [tFectReq setEntity:tEntDes];
    [tFectReq setPredicate:tPred];
    NSArray* tCheckArr= [tAppDelegate.managedObjectContext executeFetchRequest:tFectReq error:&tError];
    [tFectReq release];
    if (tError!= nil) {
        NSLog(@"check file is exits error =%@",[tError description]);
    }else {
        if ([tCheckArr count] == 0) {
            //确实没有添加纪录刷新界面
            AudioEntity* tInEntDes = (AudioEntity*)[NSEntityDescription insertNewObjectForEntityForName:@"AudioEntity" inManagedObjectContext:tAppDelegate.managedObjectContext];
            tInEntDes.musictype =[NSNumber numberWithInt:Music_LocalFile];
            tInEntDes.muiscname = [f_AddPath lastPathComponent];
            tInEntDes.muiscurl = f_AddPath;
            tInEntDes.canplay = [NSNumber numberWithInt:Music_CanPlay];
            tInEntDes.ipodfileexist = [NSNumber numberWithBool:YES];
            [tAppDelegate.managedObjectContext save:&tError];
            if (tError != nil) {
                NSLog(@"save new local music in database error =%@",[tError description]);
            }
            if (p_AllMusicItems) {
                [p_AllMusicItems release];
                p_AllMusicItems =nil;
            }
            p_AllMusicItems = [NSMutableArray arrayWithArray:[self getAllMusicLocalAndIpod:GetMusic_AllType]];
            [p_AllMusicItems retain];
            [p_ListTableView reloadData];
        }else {
            NSLog(@"music file already exist !!");
        }
    }
}


#pragma mark-
#pragma mark 音乐控制

-(void) stopMusic
{
    
}

-(void) remotePauseOrPlayMusic
{
    AudioEntity* tAEntity = [p_AllMusicItems objectAtIndex:p_NowPlayIndex];//
    if ([tAEntity.musictype intValue] == Music_IPod) {
        //系统控制
    }else if([tAEntity.musictype intValue] == Music_LocalFile){
        if ([p_LocalPlayer isPlaying]) {
            [p_LocalPlayer pause];
        }else {
            [p_LocalPlayer play];
        }
    }
}

-(void) remotePlayNextMusic
{
    AudioEntity* tAEntity = nil;
    int checkIndex = p_NowPlayIndex;
    NSIndexPath* tOldPath = [NSIndexPath indexPathForRow:p_NowPlayIndex inSection:0];
    NSMutableArray* tFlashRows = [NSMutableArray array];
    [tFlashRows addObject:tOldPath];
    do {
        p_NowPlayIndex++;
        if (p_NowPlayIndex >= [p_AllMusicItems count]) {
            p_NowPlayIndex = 0;
        }
        tAEntity = [p_AllMusicItems objectAtIndex:p_NowPlayIndex];
        if (checkIndex == p_NowPlayIndex) {
            checkIndex = -1;
            break;
        }
    } while ([tAEntity.canplay intValue] != Music_CanPlay);

    if (checkIndex < 0) {
        //没歌曲能放
    }else {
        if ([self playMusicByItem:tAEntity]) {
            NSIndexPath* tNextPath = [NSIndexPath indexPathForRow:p_NowPlayIndex inSection:0];
            [tFlashRows addObject:tNextPath];
        }
        
    }
    if ([tFlashRows count] > 0) {
        [p_ListTableView reloadRowsAtIndexPaths:tFlashRows withRowAnimation:UITableViewRowAnimationNone];
    }
}

-(void) remotePlayBackMusic
{
    AudioEntity* tAEntity = nil;
    int checkIndex = p_NowPlayIndex;
    NSIndexPath* tOldPath = [NSIndexPath indexPathForRow:p_NowPlayIndex inSection:0];
    NSMutableArray* tFlashRows = [NSMutableArray array];
    [tFlashRows addObject:tOldPath];
    do {
        p_NowPlayIndex--;
        if (p_NowPlayIndex < 0) {
            p_NowPlayIndex = [p_AllMusicItems count]-1;
        }
        tAEntity = [p_AllMusicItems objectAtIndex:p_NowPlayIndex];
        if (checkIndex == p_NowPlayIndex) {
            checkIndex = -1;
            break;
        }
    } while ([tAEntity.canplay intValue] != Music_CanPlay);
    
    if (checkIndex < 0) {
        //没歌曲能放
    }else {
        if ([self playMusicByItem:tAEntity]) {
            NSIndexPath* tNextPath = [NSIndexPath indexPathForRow:p_NowPlayIndex inSection:0];
            [tFlashRows addObject:tNextPath];
        }
        
    }
    if ([tFlashRows count] > 0) {
        [p_ListTableView reloadRowsAtIndexPaths:tFlashRows withRowAnimation:UITableViewRowAnimationNone];
    }
}

#pragma mark-
#pragma mark 底部按钮
-(void) docEditMode:(UIBarButtonItem*)f_sender
{
    if ([f_sender.title isEqualToString:@"编辑"]) {
        f_sender.title =@"完成";
        if (p_BottomBar.hidden) {
            [self showBottomTool];
        }
    }else {
        f_sender.title =@"编辑";
        if (!p_BottomBar.hidden) {
            [self hideBottomTool];
        }
    }
}

-(void) toolButtonPressed:(UIBarButtonItem*) f_sender
{
    switch (f_sender.tag) {
        case 30://导入wifi
        {
            WifiViewController* tWifiVC = [[WifiViewController alloc] init];
            if ([tWifiVC networkAvailable]) {
                tWifiVC.m_OperationPath =m_MusicPath;
                tWifiVC.m_Delegate = self;
                UINavigationController* tRootNav = [[UINavigationController alloc] initWithRootViewController:tWifiVC];
                [tWifiVC release];
                [self presentModalViewController:tRootNav animated:YES];
                [tRootNav release];
            }else {
                [tWifiVC release];
                UIAlertView* tAlertWifi = [[UIAlertView alloc] initWithTitle:@"友情提示" message:@"没有检测到wifi信号请稍后再试！" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles: nil];
                [tAlertWifi show];
                [tAlertWifi release];
            }
        }
            break;
        case 31://ftp
        {
            AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
            UINavigationController* tRootNav = (UINavigationController*)tAppDel.window.rootViewController;
            RootViewController* tRootVC = (RootViewController*)[tRootNav.viewControllers objectAtIndex:0];
            [tRootVC FTPServerShow:m_MusicPath];
        }
            break;
        case 32://同步
        {
            [p_MusicController showMediaPicker];
        }
            break;
        case 33://播放顺序
        {
            if(p_PlayMode == MusicPlay_ShunXu){
                [f_sender setTitle:@"随机播放"];
                p_PlayMode = MusicPlay_Suiji;
            }else if(p_PlayMode == MusicPlay_Suiji){
                [f_sender setTitle:@"单曲循环"];
                p_PlayMode = MusicPlay_DanXunHuan;
            }else if(p_PlayMode == MusicPlay_DanXunHuan){
                [f_sender setTitle:@"顺序播放"];
                p_PlayMode = MusicPlay_ShunXu;
            }
        }
            break;
    }
}

-(void) showBottomTool
{
    p_BottomBar.alpha =0;
    p_BottomBar.hidden =NO;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.3f];
    p_BottomBar.alpha =1.0f;
    p_ListTableView.frame =CGRectMake(0, 40, 320, 480-144);
    [UIView commitAnimations];
}
-(void) hideBottomTool
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.3f];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationStop)];
    p_BottomBar.alpha =0.f;
    p_ListTableView.frame =CGRectMake(0, 40, 320, 480-104);
    [UIView commitAnimations];
}
-(void)animationStop
{
    p_BottomBar.hidden =YES;
}

#pragma mark-
#pragma mark 其他函数
/**
 检查数据库内还没转化的 ipod 音乐对象 继续转化
 */
-(void) checkIpodMusicContinueTrans
{
    AppDelegate* tAppDelegate =(AppDelegate*)[UIApplication sharedApplication].delegate;
    NSError* tError = nil;
    NSEntityDescription* tEntDes = [NSEntityDescription entityForName:@"AudioEntity" inManagedObjectContext:tAppDelegate.managedObjectContext];
    NSFetchRequest* tFectReq = [[NSFetchRequest alloc] init];
    [tFectReq setEntity:tEntDes];
    NSPredicate* tIpodPre =[NSPredicate predicateWithFormat:@"(musictype == %d)AND(ipodfileexist == NO)",Music_IPod];
    [tFectReq setPredicate:tIpodPre];
    NSArray* tAllMusic= [tAppDelegate.managedObjectContext executeFetchRequest:tFectReq error:&tError];
    [tFectReq release];
    if (tError!= nil) {
        NSLog(@"checkIpodMusicContinueTrans predicate error =%@",[tError description]);
    }else {
        NSMutableDictionary* tMDic = [NSMutableDictionary dictionary];
        MPMediaQuery *myPlaylistsQuery = [MPMediaQuery songsQuery];  
        NSArray *playlists = [myPlaylistsQuery collections];  
        for (MPMediaPlaylist *playlist in playlists) {  
            NSArray *songs = [playlist items];  
            for (MPMediaItem *song in songs) {  
                NSString* tName= [song valueForProperty:MPMediaItemPropertyTitle];
                NSURL* tAssetUrl = [song valueForProperty:MPMediaItemPropertyAssetURL];
                [tMDic setValue:tAssetUrl forKey:tName];
            }  
        }
        NSMutableString* tDelName = [NSMutableString string];
        for (AudioEntity* tAEntity in tAllMusic) {
            NSMutableDictionary* tAddDic = [NSMutableDictionary dictionary];
            NSString* tRealURL = [tMDic objectForKey:tAEntity.muiscname];
            if (tRealURL != nil) {
                [tAddDic setValue:[tMDic objectForKey:tAEntity.muiscname] forKey:@"URL"];
                [tAddDic setValue:tAEntity.musicasseturl forKey:@"PATH"];
                [p_MusicController addTransMission:tAddDic];
            }else {
                [tDelName appendString:tAEntity.muiscname];
                [tDelName appendString:@","];
                //需要转换的音乐已经不在ipod 列表里了 删除数据库
                [tAppDelegate.managedObjectContext deleteObject:tAEntity];
            }
        }
        if ([tDelName length] >0) {
            NSString* tAllName = [tDelName substringWithRange:NSMakeRange(0, [tDelName length]-1)];
            
            UIAlertView* tTipAlert = [[UIAlertView alloc] initWithTitle:@"友情提醒" message:[NSString stringWithFormat:@"您所选的音乐(%@)在ipod内已经删除！无法继续转换到本地！",tAllName] delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [tTipAlert show];
            [tTipAlert release];
            [tAppDelegate.managedObjectContext save:&tError];
            if (tError != nil) {
                NSLog(@"delete music object from data error =%@",[tError description]);
            }else {
                if (p_AllMusicItems) {
                    [p_AllMusicItems release];
                    p_AllMusicItems =nil;
                }
                p_AllMusicItems = [NSMutableArray arrayWithArray:[self getAllMusicLocalAndIpod:GetMusic_AllType]];
                [p_AllMusicItems retain];
                [p_ListTableView reloadData];
            }
        }
    }
}

-(void) MPMusicStateChanged:(NSNotification*)f_Changed
{
    NSLog(@"%@",[f_Changed description]);
}

-(void) musicButtonPressed:(UIButton*) sender
{
    int tType = sender.tag;
    switch (tType) {
        case 0://停止
        {
            if ([p_LocalPlayer isPlaying]) {
                [p_LocalPlayer stop];
                [p_LocalPlayer release];
                p_LocalPlayer = nil;
                int oldIndex = p_NowPlayIndex;
                p_NowPlayIndex = -1;
                NSIndexPath* tNewPath = [NSIndexPath indexPathForRow:oldIndex inSection:0];
                [p_ListTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:tNewPath] withRowAnimation:UITableViewRowAnimationNone];
                UIButton* tPlayBtt = (UIButton*)[p_PlayButtonView viewWithTag:2];
                [tPlayBtt setBackgroundImage:p_PlayImg forState:UIControlStateNormal];
            }
        }
            break;
        case 1: //上一首
        {
            if ([p_AllMusicItems count] > 0) {
                [self remotePlayBackMusic];
            }
        }
            break;
        case 2: //播放／暂停  －－－播放就直接从第一首开始
        {
            if ([p_LocalPlayer isPlaying]) {
                [sender setBackgroundImage:p_PlayImg forState:UIControlStateNormal];
                [p_LocalPlayer pause];
                return;
            }
            if (p_LocalPlayer) {
                [sender setBackgroundImage:p_PauseImg forState:UIControlStateNormal];
                [p_LocalPlayer play];
                return;
            }
            p_NowPlayIndex = -1;
            AudioEntity* tPlayEntity = nil;
            for (int i=0; i<[p_AllMusicItems count]; i++) {
                tPlayEntity = [p_AllMusicItems objectAtIndex:i];
                if ([tPlayEntity.canplay intValue] == Music_CanPlay) {
                    p_NowPlayIndex = i;
                    break;
                }
            }
            if (p_NowPlayIndex >=0) {
                if ([self playMusicByItem:tPlayEntity]) {
                    [sender setBackgroundImage:p_PauseImg forState:UIControlStateNormal];
                    NSIndexPath* tNewPath = [NSIndexPath indexPathForRow:p_NowPlayIndex inSection:0];
                    [p_ListTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:tNewPath] withRowAnimation:UITableViewRowAnimationNone];
                }
            }
        }
            break;
        case 3: //下一首
        {
            if ([p_AllMusicItems count] > 0) {
                [self remotePlayNextMusic];
            }
        }
            break;
    }
}

-(BOOL) playMusicByItem:(AudioEntity*)f_NowItem
{
    if (p_LocalPlayer) {
        if ([p_LocalPlayer isPlaying]) {
            [p_LocalPlayer stop];
        }
        [p_LocalPlayer release];
        p_LocalPlayer = nil;
    }
    AVAudioSession *session = [AVAudioSession sharedInstance];  
    NSError *tActivationError = nil;
    [session setCategory:AVAudioSessionCategoryPlayback error:&tActivationError];
    if (tActivationError != nil) {
        NSLog(@" set tActivationError =%@",[tActivationError description]);
        return NO;
    }
    [session setActive:YES error:&tActivationError]; 
    if (tActivationError!= nil) {
        NSLog(@"tActivationError =%@",[tActivationError description]);
        return NO;
    }
    NSError* tError = nil;
    NSString* tEncodeURL = nil;
    if ([f_NowItem.musictype intValue] == Music_LocalFile) {
        
        tEncodeURL = [f_NowItem.muiscurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
    }else if([f_NowItem.musictype intValue] == Music_IPod){
        
        tEncodeURL = [f_NowItem.musicasseturl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
    }
    p_LocalPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:tEncodeURL] error:&tError];
    if (tError != nil) {
        NSLog(@"init local music file error =%@",[tError description]);
        f_NowItem.canplay = [NSNumber numberWithInt:Music_CanNotPlay];
        AppDelegate* tAppDelegate =(AppDelegate*)[UIApplication sharedApplication].delegate;
        NSError* tError = nil;
        [tAppDelegate.managedObjectContext save:&tError];
        if (tError != nil) {
            NSLog(@"change music file to not play state error =%@",[tError description]);
        }
        [self autoPlayNextByAnyMode];
        return NO;
    }else {
        p_LocalPlayer.delegate = self;
        [self setMediaInfo:p_PlayImg andTitle:f_NowItem.muiscname andArtist:@"未知"];
        [p_LocalPlayer prepareToPlay];
        [p_LocalPlayer play];
        
        [p_PlayName setText:f_NowItem.muiscname];
        p_TimerSlider.maximumValue = p_LocalPlayer.duration;
        int tMin = p_LocalPlayer.duration/60;
        int tSec = (int)p_LocalPlayer.duration%60;
        [p_TimeMusic setText:[NSString stringWithFormat:@"%d:%d",tMin,tSec]];
        if (p_SliderCheckTimer) {
            [p_SliderCheckTimer invalidate];
            [p_SliderCheckTimer release];
            p_SliderCheckTimer = nil;
        }
        p_SliderCheckTimer =[NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(musicSliderUpdate) userInfo:nil repeats:YES];
        [p_SliderCheckTimer retain];
    }
    return YES;
}

- (void) setMediaInfo : (UIImage *) img andTitle : (NSString *) title andArtist : (NSString *) artist
{
    if (NSClassFromString(@"MPNowPlayingInfoCenter")) {
        NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
        [dict setObject:title forKey:MPMediaItemPropertyTitle];
        [dict setObject:title forKey:MPMediaItemPropertyAlbumTitle];
        [dict setObject:artist forKey:MPMediaItemPropertyArtist];
        [dict setObject:[NSNumber numberWithInt:p_NowPlayIndex] forKey:MPMediaItemPropertyPlaybackDuration];
        
        if (img) {
            MPMediaItemArtwork * mArt = [[MPMediaItemArtwork alloc] initWithImage:img];
            [dict setObject:mArt forKey:MPMediaItemPropertyArtwork];
            [mArt release];
        }
        //[MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = nil;
        [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
        [dict release];
    }
}

#pragma mark-
#pragma mark AVAudioPlayerDelegate
/* audioPlayerDidFinishPlaying:successfully: is called when a sound has finished playing. This method is NOT called if the player is stopped due to an interruption. */
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [self autoPlayNextByAnyMode];
}

/* if an error occurs while decoding it will be reported to the delegate. */
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error
{
    AudioEntity* tErrorEntity = [p_AllMusicItems objectAtIndex:p_NowPlayIndex];
    tErrorEntity.canplay = [NSNumber numberWithInt:Music_CanNotPlay];
    AppDelegate* tAppDelegate =(AppDelegate*)[UIApplication sharedApplication].delegate;
    NSError* tError = nil;
    [tAppDelegate.managedObjectContext save:&tError];
    if (tError != nil) {
        NSLog(@"change music file to not play state error =%@",[tError description]);
    }
    [self autoPlayNextByAnyMode];
}


-(void) autoPlayNextByAnyMode
{
    AudioEntity* tAEntity = nil;
    int checkIndex = p_NowPlayIndex;
    NSIndexPath* tOldPath = [NSIndexPath indexPathForRow:p_NowPlayIndex inSection:0];
    NSMutableArray* tFlashRows = [NSMutableArray array];
    [tFlashRows addObject:tOldPath];
    if (p_PlayMode == MusicPlay_ShunXu) {
        do {
            p_NowPlayIndex++;
            if (p_NowPlayIndex >= [p_AllMusicItems count]) {
                p_NowPlayIndex = 0;
            }
            tAEntity = [p_AllMusicItems objectAtIndex:p_NowPlayIndex];
            if (checkIndex == p_NowPlayIndex) {
                checkIndex = -1;
                break;
            }
        } while ([tAEntity.canplay intValue] != Music_CanPlay);
    }else if(p_PlayMode == MusicPlay_Suiji){
        do {
            int tMaxtCount = [p_AllMusicItems count];
            p_NowPlayIndex = arc4random()%(tMaxtCount);
            tAEntity = [p_AllMusicItems objectAtIndex:p_NowPlayIndex];
        } while ([tAEntity.canplay intValue] != Music_CanPlay || checkIndex == p_NowPlayIndex);
    }else if(p_PlayMode == MusicPlay_DanXunHuan){
        tAEntity = [p_AllMusicItems objectAtIndex:p_NowPlayIndex];
        if ([tAEntity.canplay intValue]== Music_CanNotPlay) {
            checkIndex = -1;
        }
    }
    if (checkIndex < 0) {
        //没歌曲能放
        p_NowPlayIndex = -1;
    }else {
        if ([self playMusicByItem:tAEntity]) {
            NSIndexPath* tNextPath = [NSIndexPath indexPathForRow:p_NowPlayIndex inSection:0];
            [tFlashRows addObject:tNextPath];
        }
    }
    if ([tFlashRows count] > 0) {
        [p_ListTableView reloadData];
    }
    
}

#pragma mark-
#pragma mark WifiAddFileProtocol
-(void) fileAddByWifiFinish:(NSString*) f_FilePath
{
    [self addMusicItemByPath:f_FilePath];
}
-(void) fileDeleteByWifiFinish:(NSString*) f_FilePath
{
    [self deleteMusicItemByPath:f_FilePath];
}

#pragma mark-
#pragma mark AudiFileChangedByFTP
-(void) addFileByFTP:(NSString*)f_Path
{
    [self addMusicItemByPath:f_Path];
}
-(void) delFileByFTP:(NSString*)f_Path
{
    [self deleteMusicItemByPath:f_Path];
}
-(void) reNameFileByFTP:(NSString*)f_Path oldName:(NSString*)f_OldName
{
    AppDelegate* tAppDelegate =(AppDelegate*)[UIApplication sharedApplication].delegate;
    NSError* tError = nil;
    //检查是已经有此条纪录
    NSEntityDescription* tEntDes = [NSEntityDescription entityForName:@"AudioEntity" inManagedObjectContext:tAppDelegate.managedObjectContext];
    NSPredicate* tPred = [NSPredicate predicateWithFormat:@"muiscurl == %@",f_OldName];
    NSFetchRequest* tFectReq = [[NSFetchRequest alloc] init];
    [tFectReq setEntity:tEntDes];
    [tFectReq setPredicate:tPred];
    NSArray* tCheckArr= [tAppDelegate.managedObjectContext executeFetchRequest:tFectReq error:&tError];
    [tFectReq release];
    if (tError!= nil) {
        NSLog(@"check file is exits error =%@",[tError description]);
    }else {
        if ([tCheckArr count] ==1) {
            AudioEntity* tChNameEntity = [tCheckArr objectAtIndex:0];
            tChNameEntity.muiscurl = f_Path;
            tChNameEntity.muiscname = [f_Path lastPathComponent];
            [tAppDelegate.managedObjectContext save:&tError];
            if (tError != nil) {
                NSLog(@"reNameFileByFTP music in database error =%@",[tError description]);
            }
            if (p_AllMusicItems) {
                [p_AllMusicItems release];
                p_AllMusicItems =nil;
            }
            p_AllMusicItems = [NSMutableArray arrayWithArray:[self getAllMusicLocalAndIpod:GetMusic_AllType]];
            [p_AllMusicItems retain];
            [p_ListTableView reloadData];
        }else {
            NSLog(@"reNameFileByFTP file not exists or more same files!!");
        }
    }
}

#pragma mark-
#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        
    }else{
        NSUserDefaults* tUDefault =[NSUserDefaults standardUserDefaults];
        [tUDefault setValue:[NSNumber numberWithBool:NO] forKey:MusicAlert];
        [tUDefault synchronize];
    }
}


@end
